package name.marz.to.go.ahg.core;

import java.net.URI;
import java.util.logging.Logger;

import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.protocol.HttpContext;

/**
 * AutoGetterのリダイレクトストラテジーです<br>
 * POSTのリダイレクトをGETに変換します
 * @author mgoto
 *
 */
public class AutoGetterRedirectStrategy extends DefaultRedirectStrategy {
	private static final Logger log = Logger.getLogger(AutoGetterRedirectStrategy.class.getName());
	public boolean isRedirected(
              final HttpRequest request,
              final HttpResponse response,
              final HttpContext context) throws ProtocolException {
          if (response == null) {
              throw new IllegalArgumentException("HTTP response may not be null");
          }
  
          int statusCode = response.getStatusLine().getStatusCode();
          Header locationHeader = response.getFirstHeader("location");
          switch (statusCode) {
          case HttpStatus.SC_MOVED_TEMPORARILY:
              return locationHeader != null;
          case HttpStatus.SC_MOVED_PERMANENTLY:
          case HttpStatus.SC_TEMPORARY_REDIRECT:
              return true;
          case HttpStatus.SC_SEE_OTHER:
              return true;
          default:
              return false;
          } //end of switch
      }

	@Override
	public HttpUriRequest getRedirect(HttpRequest request,
			HttpResponse response, HttpContext context)
			throws ProtocolException {
		
		String method = request.getRequestLine().getMethod();
		log.fine("応答sts="+response.getStatusLine());
		if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
			URI uri = getLocationURI(request, response, context);
			HttpGet post = new HttpGet(uri);
			log.fine("return get method ");
			return post;
		} else {
			return super.getRedirect(request, response, context);
		}
	}
}
